package org.budo.dubbo.protocol.http.page;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.support.freemarker.FreemarkerUtil;
import org.budo.support.lang.util.ReflectUtil;

/**
 * @author lmw
 */
public abstract class AbstractPage extends HttpServlet {
    private static final long serialVersionUID = -2637190522664955592L;

    public static final boolean HAS_SWAGGER = ReflectUtil.hasClass("io.swagger.annotations.Api");

    public enum Scope {
        Public, Private, All, Controller, RequestMapping;
    }

    protected Scope getScope(HttpServletRequest request) {
        String scopeStr = request.getParameter("scope");

        if (null == scopeStr) {
            return Scope.Public; // 默认展示公共接口
        }

        if ("private".equalsIgnoreCase(scopeStr)) {
            return Scope.Private;
        }

        if ("all".equalsIgnoreCase(scopeStr)) {
            return Scope.All;
        }

        if ("Controller".equalsIgnoreCase(scopeStr)) {
            return Scope.Controller;
        }

        if ("RequestMapping".equalsIgnoreCase(scopeStr)) {
            return Scope.RequestMapping;
        }

        return Scope.Public;
    }

    protected void renderPage(String templateInput, Map<String, Object> dataMap, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (null != dataMap && null != request && !dataMap.containsKey("RequestParameters")) {
            Map<String, Object> requestParameters = new HashMap<String, Object>();
            Map<String, String[]> parameterMap = request.getParameterMap();
            Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
            for (Entry<String, String[]> entry : entrySet) {
                String[] value = entry.getValue();
                if (null == value) {
                    continue;
                }

                if (value.length < 2) {
                    requestParameters.put(entry.getKey(), value[0]);
                } else {
                    requestParameters.put(entry.getKey(), value);
                }
            }
            dataMap.put("RequestParameters", requestParameters);
        }

        FreemarkerUtil.freemarkerRender(templateInput, dataMap, response.getOutputStream());
    }
}